#include <QDebug>
#include <QFileInfo>
#include <QPushButton>
#include "RenameDlg.h"
#include "ui_RenameDlg.h"

RenameDlg::RenameDlg(const QString &path, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RenameDlg)
{
    QFileInfo info(path);
    _path = info.absolutePath();
    _name = info.fileName();

    ui->setupUi(this);
    ui->nameEdt->setText(_name);
    connect(ui->buttonBox, SIGNAL(rejected()), SLOT(reject()));
    connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onAccepted()));
    connect(ui->nameEdt, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
    ui->lblErr->hide();
}

RenameDlg::~RenameDlg()
{
    delete ui;
}

void RenameDlg::onAccepted()
{
    QFile::rename(_path+"/"+_name, _path+"/"+ui->nameEdt->text());
    accept();
}

void RenameDlg::onTextChanged(const QString & text)
{
    bool exists = QFile::exists(_path+"/"+text);
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(text != _name && !exists);
    if (text == _name){
        ui->lblErr->setText(tr("Nothing to rename"));
    } else if (exists){
        ui->lblErr->setText(tr("File '%1' already exists.").arg(text));
    }
    ui->lblErr->setVisible(text == _name || exists);
}

